<!-- 创建、修改任务-->
<template>
  <Modal
    v-model="modal.show"
    :title="modal.title"
    :loading="modal.loading"
    :mask-closable="false"
    @on-ok="saveTask"
    @on-cancel="closeModal"
    :width="modal.width"
  >
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="60">
      <FormItem label="名称" prop="name">
        <Input
          v-model.trim="formValidate.name"
          placeholder="请输入中文、数字、字母、英文括号、下划线或者中划线，名称长度为1-50个字符"
          :maxlength="50"
        ></Input>
      </FormItem>
      <FormItem label="人员" prop="taskUserList">
        <Select filterable v-model="selectGroups" placeholder="请选择角色" @on-change="selectGroup" multiple>
          <Option v-for="group in accessGroupList" :key="group.id" :value="group.id" filterable>
            {{ group.name }}
          </Option>
        </Select>
        <div>
          <CheckboxGroup v-model="formValidate.taskUserList">
            <Checkbox :label="user.userId" v-for="user in optionalUsers" :key="user.userId">
              {{ user.userName }}
            </Checkbox>
          </CheckboxGroup>
        </div>
      </FormItem>
      <FormItem label="描述" prop="description">
        <Input
          v-model.trim="formValidate.description"
          type="textarea"
          :maxlength="200"
          :autosize="{ minRows: 2, maxRows: 5 }"
          placeholder="请输入描述"
        ></Input>
      </FormItem>
      <!-- <FormItem label="任务附件" prop="writeUpPath">
            <section>
                <Row>
                    <Upload ref="upload" 
                        :action="uploadAction" 
                        :show-upload-list="false" 
                        :format="['doc','docx','pdf']" 
                        :on-format-error="handleFormatError" 
                        :on-success="getImageUrl" 
                        :on-progress="getProgress" 
                        :before-upload="handleBeforeUpload" 
                        :max-size="20480" 
                        :on-exceeded-size="handleUploadSize" 
                        :headers="uploadHeader" style="display:inline-block;">
                        <Button icon="ios-cloud-upload-outline" :disabled="uploadList.length > 0">上传漏洞说明文档</Button>
                    </Upload>
                    <Tooltip style="margin-left: 10px;" :transfer='true' max-width="200" content="请上传doc,docx,pdf等格式文件,文件大小不能超过20M" placement="top">
                        <Icon type="ios-alert" class="ios-alert" />
                    </Tooltip>	
                </Row>
                <div class="demo-upload-list" v-for="item in uploadList">
                    <template v-if="item.status === 'finished'">
                    </template>
                    <template v-else>
                        <span style="margin-right:5px;">文件名：{{item.name}}</span> <span style="margin-right:5px;">文件大小：{{getFileSize(item.size)}}</span> <span style="margin-right:5px;">上传速度：{{speed}}</span>
                        <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                    </template>
                </div>
                <div class="chose-wrap" v-show="filename">
                        <div style="display: flex;justify-content: flex-start;align-items: center">
                            <img src="../../../../../assets/exper/guide.png" class="chose-s2-icon">
                            <div class="chose-name">{{filename}}</div>
                        </div>
                        <img src="../../../../../assets/globalIcon/dis-del.png" style="width: 13px;height: 14px;cursor: pointer" @click="clearDoc">
                </div>
                <p v-if="showTip" style="color:red;">请上传doc,pdf格式文件,文件大小不能超过20M</p>
                <div class="ivu-form-item-error-tip" v-if="uploaderror">请上传文件</div>
            </section>
        </FormItem> -->
    </Form>
  </Modal>
</template>
<script>
// import { validateName } from '@/libs/reg'
import { validateName } from './taskMixin';
import { getaccessgrouplist } from '@/api/access_new';
import { addTask, updateTask } from '@/api/process/task';
export default {
  name: 'EditModal',
  props: {
    testId: {
      type: String,
      required: true
    }
  },
  data() {
    const validateFile = (rule, value, callback) => {
      if (!value) {
        callback('请选择文件');
      } else if (value.split('.').pop() !== 'json') {
        callback('请选择文件');
      }
      callback();
    };
    return {
      modal: {
        show: this.value,
        title: '添加任务',
        loading: true,
        width: 500
      },
      formValidate: {
        description: '',
        name: '',
        taskMode: 'normal',
        taskType: 'EYDD',
        testId: this.testId,
        taskUserList: []
      },
      ruleValidate: {
        name: [
          {
            required: true,
            max: 50,
            message: '任务名称长度为1-50个字符',
            trigger: 'blur'
          },
          {
            validator: validateName,
            trigger: 'blur'
          }
        ],
        taskUserList: [{ required: true, type: 'array', min: 1, message: '请至少选择一个人员' }],
        description: [{ max: 200, message: '描述长度不能超过200个字符', trigger: 'blur' }]
      },
      accessGroupList: [],
      selectGroups: [],
      optionalUsers: []
    };
  },
  computed: {},
  watch: {},
  mounted() {
    this._formValidate = { ...this.formValidate };
  },
  methods: {
    saveTask() {
      this.$refs.formValidate
        .validate((valid) => {
          if (valid) {
            let params = {
              ...this.formValidate,
              taskUserList: this.formValidate.taskUserList.map((userId) => {
                return { userId };
              })
            };
            if (this.type === 'update') {
              //修改任务
              updateTask(this.formValidate.id, params)
                .then(({ code, data, message }) => {
                  if (code == 1) {
                    this.$Message.info('修改任务成功');
                    this.closeModal();
                    this.$emit('ok', 'update');
                  } else {
                    this.$Message.error(message);
                  }
                })
                .catch((e) => {
                  this.$Message.error('修改任务失败');
                })
                .finally(() => {
                  this.cancelLoading();
                });
            } else {
              // 添加任务
              addTask(params)
                .then(({ code, data, message }) => {
                  if (code == 1) {
                    this.$Message.info('添加任务成功');
                    this.closeModal();
                    this.$emit('ok', 'add');
                  } else {
                    this.$Message.error(message);
                  }
                })
                .catch((e) => {
                  this.$Message.error('添加任务失败');
                })
                .finally(() => {
                  this.cancelLoading();
                });
            }
          } else {
            this.cancelLoading();
          }
        })
        .catch((error) => {
          this.cancelLoading();
        });
    },
    initData() {
      this.formValidate = { ...this._formValidate };
      this.selectGroups = [];
      this.optionalUsers = [];
    },
    resetField() {
      this.initData();
      this.$refs.formValidate.resetFields();
    },
    async showModal(data) {
      this.type = data ? 'update' : 'add';
      this.modal.show = true;
      if (this.type == 'update') {
        await this.getAccessGroupList();
        this.modal.title = '修改任务';
        let taskUserList = data.taskUserList.map((user) => user.userId);
        this.formValidate = { ...data, ...{ taskUserList } };
        let selectGroups = this.accessGroupList.filter((group) => {
          let groupUserList = group.userList.map((user) => user.userId);
          let result =
            groupUserList.length + taskUserList.length !==
            Array.from(new Set([...groupUserList, ...taskUserList])).length;
          return result;
        });
        this.storeSaveUserList = taskUserList.length > 0 ? taskUserList : '';
        this.prevUserIds = '';
        this.selectGroups = selectGroups.map((group) => group.id);
        // let users = selectGroups.reduce((users,group,index) => {
        //     return [...users,...group.userList]
        // },[])
        // this.optionalUsers = users;
        // setTimeout(() => {

        // })
      } else {
        this.modal.title = '添加任务';
        this.getAccessGroupList();
        this.initData();
      }
    },
    closeModal() {
      this.modal.show = false;
      this.$emit('close');
      this.resetField();
    },
    cancelLoading() {
      this.modal.loading = false;
      setTimeout(() => {
        this.modal.loading = true;
      });
    },
    // 查询竞赛、演练接入组列表
    getAccessGroupList() {
      if (!this.testId) {
        return;
      }
      return new Promise((resolve, reject) => {
        let params = {
          pageIndex: 1,
          pageSize: 2147483647,
          testId: this.testId
        };
        getaccessgrouplist(params).then(
          ({ code, data: { items: accessGroupList = [] }, message }) => {
            if (code == 1) {
              this.accessGroupList = accessGroupList.filter((item) => item.userList.length > 0);
              resolve();
            } else if (code == -2) {
              this.accessGroupList = [];
            } else {
              this.$Message.warning(message);
            }
          }
        );
      });
    },
    selectGroup(list) {
      let users = list.reduce((users, groupId, index) => {
        let group = this.accessGroupList.find((group) => group.id === groupId);
        return [...users, ...group.userList];
      }, []);
      // 去掉现在没有的
      let userIds = users.map((user) => user.userId); 
      this.formValidate.taskUserList = this.formValidate.taskUserList.filter((userId) =>
        userIds.includes(userId)
      );
      //新添加的用户默认选中
      if (this.prevUserIds) {
        let addUsers = userIds.filter((userId) => !this.prevUserIds.includes(userId));
        this.formValidate.taskUserList = [...this.formValidate.taskUserList, ...addUsers];
      } else {
        this.formValidate.taskUserList = this.storeSaveUserList || userIds;
        this.storeSaveUserList = '';
      }
      this.optionalUsers = users;
      // 上次选择的
      this.prevUserIds = userIds;
    }
  }
};
</script>
<style scoped></style>
